from Components.ActionMap import ActionMap
from Components.MenuList import MenuList
from Components.Label import Label
from Screens.Screen import Screen
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Components.config import config, ConfigSubsection, ConfigText, ConfigBoolean
from enigma import iPlayableService, iServiceInformation

import os, os.path, socket, re

dmnapi_py = "/usr/lib/enigma2/python/Plugins/Extensions/DMnapi/dmnapi.py"
dmnapi_ins = "/usr/lib/enigma2/python/Plugins/Extensions/DMnapi/dmnapiinst.py"
dmnapi_version = "13.1.30"

config.plugins.DMnapi = ConfigSubsection()
config.plugins.DMnapi.encoding = ConfigText(default = "utf-8-sig")
config.plugins.DMnapi.audiomenu = ConfigBoolean(default = True)
config.plugins.DMnapi.save()
print "DMnapi:", config.plugins.DMnapi.encoding.value

def check_newver( method = 'dns' ):
    t = socket.getdefaulttimeout()
    socket.setdefaulttimeout(2)
    try:
	if method == 'dns':
		latest = socket.gethostbyname('dmnapi.areq.eu.org')
		q = re.match(r"(1[12345])\.(1?\d)\.(\d+)\.([01234])", latest).groups(0)
		if q[3] == '0':
			new = ".".join(q[0:3])
		else:
			new = ".".join(q[0:4])
	else:
		import urllib2
		new = re.search('Latest version: .strong.(.*)..strong', urllib2.urlopen('http://code.google.com/p/dmnapi/wiki/DMnapi').read(),re.MULTILINE ).group(1)
    except:
		new = dmnapi_version
    socket.setdefaulttimeout(t)
    return new

def wagver(v):
    return "".join(map(lambda x: x.rjust(2,'0'), (v + '.0').split('.')[0:4]))

class N24Screen(Screen):
	skin="""
		<screen name="N24Screen" position="0,0" size="720,576" title="Napisy24" backgroundColor="#002C2C39">
			<widget name="list" position="0,0" size="720,576" zPosition="1" alphatest="on" />
		</screen>"""

	def __init__(self, session, list = None):
		Screen.__init__(self, session)
		self["list"] = ChoiceBox(title = "napisy24", list = list)
		self["myActionMap"] = ActionMap(["SetupActions"],
		{
			"ok": self.cancel,
			"cancel": self.cancel
		}, -1)
	def cancel(self):
		print "[N24Screen] - cancel\n"
		self.close(None)

class DMnapi(Screen):
	skin = """
		<screen position="280,220" size="500,200" title="DMnapi by areq" >
			<widget name="menu" position="5,80" size="490,180" scrollbarMode="showOnDemand" />
			<widget name="label" position="5,5" size="490,60" font="Regular;18" halign="left" />
		</screen>"""

	def __init__(self, session, args = None):
		try:
		    os.chmod(dmnapi_py, 0555)
		    os.chmod(dmnapi_ins, 0555)
		except:
		    pass
		Screen.__init__(self, session)
		self.session = session
		self["label"] = Label("Hint: in DreamExpoler use TEXT button")
		self.plik = "q/q"
		self.newver = dmnapi_version
		self.amenu = False
		self.fps = 0
		list = []
		
		if args == 'amenu':
			service = self.session.nav.getCurrentService()
			info = service and service.info()
			height = info and info.getInfo(iServiceInformation.sVideoHeight)
			width = info and info.getInfo(iServiceInformation.sVideoWidth)
			self.fps = info and info.getInfo(iServiceInformation.sFrameRate)
#			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
#			self.session.nav.stopService() # try to disable foreground service
#			self.session.nav.playService(self.oldref)
			args = self.session.nav.getCurrentlyPlayingServiceReference().toString()
			if args.startswith("4097:"):
				args = args.split(':')[10]
				self.amenu = True
			else:
				args = None
			print "DMnapi: CurrentlyPlayingServiceReference", args
		if args is not None:
			self.plik = args
			(path, file) = os.path.split(self.plik)
			ext = file[-3:]
			self.skin = """
		<screen position="center,center" size="900,480" title="DMnapi by areq ver: %s" >
			<widget name="label" position="0,0" size="900,60" font="Regular;18" halign="left" />
			<widget name="menu" position="10,60" size="900,480" scrollbarMode="showOnDemand" />
		</screen>""" % dmnapi_version

			self["label"] = Label("Path: %s\nFile: %s\n" % ( path, file) )
			list.append((_("Pobierz napisy z NapiProjekt"), "getnapi"))
			list.append((_("Pobierz napisy z napisy24.pl"), "napisy24"))
			list.append((_("Uzupelnij napisy dla *." + ext ), "getnapiallnew"))
			list.append((_("Pobierz napisy dla wszystkich *." + ext ), "getnapiall"))
			list.append((_("Konwertuj istniejace napisy"), "convert"))
			list.append(( "----", ""))
			
		list.append(("Install Gemini/DreamExplorer integration", "install_dmnapi"))
		self.newver = check_newver()
		print "[DMnapi] newverrr:", self.newver
		if wagver(self.newver) >  wagver(dmnapi_version):
			print "[DMnapi] newver22:", self.newver
			list.append(("Upgrade to new version: %s" % self.newver, "upgrade"))
		list.append(("About DMnapi", "about_dmnapi"))
		self["menu"] = MenuList(list)
		self["actions"] = ActionMap(["OkCancelActions"], {"ok": self.run, "cancel": self.close}, -1)

	def run(self, val = False):
		returnValue = self["menu"].l.getCurrentSelection()[1]
		if returnValue is not None:
			path, video =  os.path.split(self.plik)
			print "[DMnapi] menucb :%s:" % returnValue 
			if returnValue == "getnapi":
				self.session.openWithCallback(self.poPobraniu, Console,_("Download subtitle:"),['%s get %s "%s"' % (dmnapi_py, self.fps, self.plik )])
				self.close(None)
			elif returnValue == "getnapiall":
				self.session.open(Console,_("Download subtitle:"),['%s all %s "%s"' % (dmnapi_py, self.fps, self.plik )])
			elif returnValue == "getnapiallnew":
				self.session.open(Console,_("Download subtitle:"),['%s allnew %s "%s"' % (dmnapi_py, self.fps, self.plik )])
			elif returnValue == "upgrade":
				self.Upgrade(self.newver)
			elif returnValue == "convert":
				askList = []
				for file in os.listdir(path):
				    if file.lower().endswith( ('.txt', '.sub', '.srt') ):
				            if 100 < os.path.getsize(os.path.join(path,file)) < 200000:
				                        askList.append([file, os.path.join(path,file)])
				dei = self.session.openWithCallback(self.ConvertExecution, ChoiceBox, title="Dla " + video, list=askList)
				dei.setTitle(_("Konwersja istniejacych napisow"))
			elif returnValue == "napisy24":
				print "[DMnapi] menucb napisy24a" 
				try:
					import N24
					import dmnapim
					i = dmnapim.parse_name(video)
					if i['type'] == 'tvshow':
					    ask = 'title=%s %ix%i' % (i['name'], i['season'], i['episode'])
					else:
						imdb = dmnapim.find_imdb(self.plik)
						if imdb != '':
							ask = 'imdb=%s' % imdb
						else:
							ask = 'title=%s' % (i['name'])
					url = ('http://napisy24.pl/libs/webapi.php?' + ask).replace(' ','%20')
					print "[DMnapi] n24 url:", url
					m24res = N24.parse_n24(N24.http_n24(url).split('\n'))
					print "[DMnapi] n24 list:", m24res
					askList = []
					for x,y in m24res.items():
						askList.append(["%s %s:%s" % (y['title'],  y['language'], y['release']), x])
					dei = self.session.openWithCallback(self.n24get, ChoiceBox, title="Q: %s  type:%s\nPath:%s\nFile:%s" % (ask, i['type'], path, video), list=askList)
					dei.setTitle(_("Napisy24"))
				except:
				    pass
			elif returnValue == "install_dmnapi":
				self.session.open(Console,_("Install:"), [dmnapi_ins] )
			elif returnValue == "about_dmnapi":
				mtype = MessageBox.TYPE_INFO
				title = "DMnapi version %s compiled\nby areq from http://dvhk.pl/\n\nhttp://dmnapi.googlecode.com/" % dmnapi_version
				self.newver = check_newver( method = 'wiki')
				print "[DMnapi] newver on wiki:", self.newver
				if wagver(self.newver) > wagver(dmnapi_version):
					mtype = MessageBox.TYPE_YESNO 
					title += '\n\nNew version avaible: %s\nUpgrade ?' % self.newver
				self.session.openWithCallback(self.poAbout, MessageBox,("%s") % (title), mtype)

	def ConvertExecution(self, answer):
		answer = answer and answer[1]
		if type(answer).__name__ != 'NoneType':
			if len(answer) > 3:
				self.session.openWithCallback(self.poPobraniu, Console,_("Download subtitle:"),['%s convert %s "%s" "%s"' % (dmnapi_py, self.fps, self.plik, answer )])

	def n24get(self, answer):
		answer = answer and answer[1]
		if type(answer).__name__ != 'NoneType':
			if len(str(answer)) > 3:
				self.session.openWithCallback(self.poPobraniu, Console,_("Download subtitle n24:"),['%s n24 %s "%s" "%s"' % (dmnapi_py, self.fps, self.plik, answer )])

	def poAbout(self, answer = None):
		print "[DMnapi] poAbout answer =", answer
		if answer and wagver(self.newver) > wagver(dmnapi_version):
			self.Upgrade(self.newver)

	def poPobraniu(self, answer = None):
		print "[DMnapi] poPobraniu answer =", answer
		print "[DMnapi] poPobraniu plik =", self.plik
		if self.amenu:
			from Screens.InfoBar import MoviePlayer
			rs = MoviePlayer.ENABLE_RESUME_SUPPORT
			print "[DMnapi] poPobraniu resume =", rs 
			MoviePlayer.ENABLE_RESUME_SUPPORT = False
			oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			service = self.session.nav.getCurrentService()
			seek = service.seek()
			position = seek.getPlayPosition()[1]
			print "[DMnapi] poPobraniu position =", position , seek.isCurrentlySeekable()
			self.session.nav.stopService()
			self.session.nav.playService(oldref)
			service = self.session.nav.getCurrentService()
			pausable = service.pause()
			seek = service.seek()
			if seek.isCurrentlySeekable():
				print "[DMnapi] poPobraniu seekable"
			else: 
				print "[DMnapi] poPobraniu unseekable"
			pausable.pause()
			position2 = seek.getPlayPosition()[1]
			print "[DMnapi] poPobraniu position2 =", position2 
			seek.seekTo(position)
			pausable.unpause()
			position3 = seek.getPlayPosition()[1]
			print "[DMnapi] poPobraniu position3 =", position3
			
			MoviePlayer.ENABLE_RESUME_SUPPORT = rs

	def poUpgrade(self, answer = None):
		print "[DMnapi] po upgrade"
		import DMnapi
		reload(DMnapi)
		import N24
		reload(N24)
		import dmnapim
		reload(dmnapim)
		print "[DMnapi] po upgrade2", dmnapi_version

	def Upgrade(self, newver):
		url = "http://dmnapi.googlecode.com/files/enigma2-plugin-extensions-dmnapi_%s_all.ipk" % (newver)
		self.session.openWithCallback(self.poUpgrade, Console,_("Upgrade:"),['%s upgrade "%s"' % (dmnapi_py, url )])
